package source.display
{
	import flash.display.Sprite;
	import flash.events.*;
	import flash.geom.Rectangle;
	
	import source.xml.*;

	public class ServiceView extends Sprite implements IServiceView
	{
		
		public static const ITEM_WIDTH:Number = 150;
		public static const ITEM_HEIGHT:Number = 30;
		public static const ITEM_MARGIN:Number = 1;
		
		private var service:IXMLManager;
		private var items:Array;
		private var itemDisplays:Array;
		
		public function ServiceView( service:IXMLManager )
		{
			
//			this.opaqueBackground = true;
			this.visible = true;
			this.graphics.beginFill( 0x335566 );
			this.graphics.drawRoundRect( 0, 0, ITEM_WIDTH + 10, 200, 6, 6 );
			this.graphics.endFill();
			this.scrollRect = new Rectangle( 0, 0, 160, 200 );
//			this.y -= 20;
			
			this.items = new Array();
			this.itemDisplays = new Array();
			this.service = service;
			this.service.addEventListener( XMLManager.STATE_CHANGE, refresh );
			
		}
		
		public function refresh( event:Event ):void
		{
			
			if( service.getState() == XMLManager.AVAILABLE ) {
			
				draw();
				
			}
			
		}
		
		private function draw():void {
			
			var temp:XML = service.getService();
			
			for( var i:int=temp..item.length() - 1; i>=0; i-- ) 
			{
				
				var duplicate:Boolean = false;
				
				for( var j:int = 0; j<items.length; j++ ) {
				
					if( items[j] == temp..item[i] ) {
					
//						trace( temp..item[i].title[0] + ' is already in the array' );
						duplicate = true;
						break;
					
					} 
					
				}
				
				if( duplicate ) {
					
					trace( 'This one is a duplicate' );
					
				} else {
						
					trace( 'Adding item to array at index ' + items.length );
					items.push( temp..item[i] );
					addItemToDisplay( items[ items.length - 1 ] );
						
				}
				
			}
			
		}
		
		private function addItemToDisplay( item:XML ):void
		{
			
			var title:String = item.title[0];
			var blurb:String = item.description[0];
			var link:String = item.link[0];
			
			if( itemDisplays.length > 0 ) {
				
				shiftItemDisplays();
				
			}
			
			var itemDisplay:ItemDisplay = new ItemDisplay( title, blurb, link,
								ServiceView.ITEM_WIDTH, ServiceView.ITEM_HEIGHT );	
			itemDisplay.addEventListener( MouseEvent.CLICK, doGetLink );
			itemDisplay.x = ( this.width - itemDisplay.width ) / 2; 
			
							
			itemDisplays.push( itemDisplay ); 
			addChild( itemDisplays[ itemDisplays.length - 1 ] );
			
		}
		
		private function shiftItemDisplays():void
		{
			
			for( var i:int = 0; i<itemDisplays.length; i++ ) {
				
				itemDisplays[i].y += ServiceView.ITEM_HEIGHT + ServiceView.ITEM_MARGIN;
				
			}
			
		}
		
		private function doGetLink( event:Event ):void
		{
			
			event.currentTarget.getLink();
			
		}
		
	}
}